import React, { useState, useRef, useMemo, useEffect, useCallback } from 'react';
import { Editor } from 'ketcher-react';
import { StandaloneStructServiceProvider } from 'ketcher-standalone';
import 'ketcher-react/dist/index.css';
import axios from 'axios';
import Molecule3DViewer from './Molecule3DViewer';

// ... (propertiesConfig and API_URL remain the same)
const propertiesConfig = {
    "物理性质": ["均方回转半径", "LogP"],
    "热学性质": ["熔点", "热分解温度", "热膨胀系数"],
    "力学性质": ["密度", "粘度", "弹性模量"],
    "光学性质": ["折射率", "阿贝数（演示用）"]
};
const API_URL = 'http://localhost:5000/predict';


function App() {
  const [activeTab, setActiveTab] = useState('polymers');
  const [inputType, setInputType] = useState('draw');
  const [smilesInput, setSmilesInput] = useState('*CC*'); 
  const [components, setComponents] = useState([]);
  
  const [selectedProperties, setSelectedProperties] = useState(new Set());
  const [results, setResults] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const [isComponentsPopoverVisible, setComponentsPopoverVisible] = useState(false);
  const [isPropertiesPopoverVisible, setPropertiesPopoverVisible] = useState(false);
  
  const ketcherRef = useRef(null);
  const structServiceProvider = useMemo(() => new StandaloneStructServiceProvider(), []);
  
  const componentsPopoverTimeoutRef = useRef(null);
  const propertiesPopoverTimeoutRef = useRef(null);
  
  useEffect(() => {
    return () => {
      clearTimeout(componentsPopoverTimeoutRef.current);
      clearTimeout(propertiesPopoverTimeoutRef.current);
    };
  }, []);

  useEffect(() => {
    const fragments = smilesInput.split('.').filter(s => s.trim() !== '');
    
    setComponents(prevComponents => {
      const newComponents = fragments.map((smile, index) => {
        const existing = prevComponents.find(p => p.smiles === smile);
        return {
          id: `${smile}-${index}`,
          smiles: smile,
          ratio: existing?.ratio ?? (100 / (fragments.length || 1))
        };
      });

      if (newComponents.length === 0) return [];

      const totalRatio = newComponents.reduce((sum, c) => sum + c.ratio, 0);
      if (totalRatio === 0) {
          const evenRatio = 100 / newComponents.length;
          return newComponents.map(c => ({...c, ratio: evenRatio}));
      }

      const normalizedComponents = newComponents.map(c => ({
        ...c,
        ratio: (c.ratio / totalRatio) * 100
      }));

      return normalizedComponents;
    });
  }, [smilesInput]);


  // ... (syncFromKetcher, handleRatioChange, handlePropertyChange, handleSubmit remain the same)
    const syncFromKetcher = async () => { if (ketcherRef.current) { try { const smilesString = await ketcherRef.current.getSmiles(true); setSmilesInput(smilesString || ''); } catch (e) {  console.error("Error getting SMILES:", e);  setError("无法从绘图器获取SMILES，请确保结构有效。"); } } };
    const handleRatioChange = useCallback((changedIndex, newRatio) => { setComponents(prevComponents => { if (prevComponents.length <= 1) return prevComponents.map(c => ({...c, ratio: 100})); const newComponents = JSON.parse(JSON.stringify(prevComponents)); const oldRatio = newComponents[changedIndex].ratio; const delta = newRatio - oldRatio; newComponents[changedIndex].ratio = newRatio; const othersRatioSum = 100 - oldRatio; for (let i = 0; i < newComponents.length; i++) { if (i === changedIndex) continue; if (othersRatioSum > 1e-6) { const share = newComponents[i].ratio / othersRatioSum; newComponents[i].ratio -= delta * share; } else { newComponents[i].ratio -= delta / (newComponents.length - 1); } newComponents[i].ratio = Math.max(0, Math.min(100, newComponents[i].ratio)); } const finalSum = newComponents.reduce((sum, c) => sum + c.ratio, 0); const correctionFactor = 100 / finalSum; let correctedSum = 0; for (let i = 0; i < newComponents.length - 1; i++) { newComponents[i].ratio *= correctionFactor; correctedSum += newComponents[i].ratio; } newComponents[newComponents.length - 1].ratio = 100 - correctedSum; return newComponents; }); }, []);
    const handlePropertyChange = (prop) => { const newSelection = new Set(selectedProperties); newSelection.has(prop) ? newSelection.delete(prop) : newSelection.add(prop); setSelectedProperties(newSelection); };
    const handleSubmit = async () => { if (components.length === 0) { setError('请至少提供一个分子组分。'); return; } if (selectedProperties.size === 0) {  setError('请至少选择一个物化性质进行预测。');  return;  } setIsLoading(true); setError(''); setResults(null); const payload = { molecules: components.map(({ smiles, ratio }) => ({ smiles, ratio: parseFloat(ratio.toFixed(4)) })), properties: Array.from(selectedProperties)  }; try { const response = await axios.post(API_URL, payload); setResults(response.data); } catch (err) { const errorMessage = err.response?.data?.error || '请求失败，请检查后端服务或网络连接。'; setError(errorMessage); setResults(null); } finally { setIsLoading(false); } };

  const handlePopoverMouseEnter = (timeoutRef, setVisible) => {
    clearTimeout(timeoutRef.current);
    setVisible(true);
  };

  const handlePopoverMouseLeave = (timeoutRef, setVisible) => {
    timeoutRef.current = setTimeout(() => {
      setVisible(false);
    }, 500);
  };

  const renderResults = () => { /* ... remains the same */ if (error) return <p className="error-message">{error}</p>; if (isLoading) return <div className="results-placeholder">🚀 正在全力计算中，请稍候...</div>; if (!results) return <div className="results-placeholder">💡 预测结果将在此处显示</div>; const displayNames = {  processed_smiles: "处理后SMILES",  ri: "折射率",  abbe: "阿贝数（演示用）", mixture_info: "混合体系信息" }; return ( <> <h2 className='results-title'>预测结果</h2> {Object.entries(results).map(([key, value]) => ( <div key={key} className="result-item"> <span className="result-key">{displayNames[key] || key}</span> <span className="result-value">{typeof value === 'number' ? value.toFixed(4) : String(value)}</span> </div> ))} </> ); };
  
  const ReadmeContent = () => ( /* ... remains the same */ <div className="content readme-content"> <h2>⚠️ README: 高分子SMILES输入准则</h2> <p>为了准确预测高分子材料的性质，请输入符合规范的、代表高分子重复单元的SMILES表达式。对于共混物，请用点(<code>.</code>)分隔不同的SMILES字符串。</p> <h3>基本规则</h3> <ul> <li><strong>重复单元</strong>: SMILES字符串应该代表高分子的最小重复单元。</li> <li><strong>连接点</strong>: 使用星号 <code>*</code> 来标记重复单元的连接点。</li> <li><strong>多组分</strong>: 在文本框中或在画板上绘制多个不相连的结构，它们将被自动识别为不同的组分。</li> </ul> </div> );


  // --- MODIFICATION START: Dynamic button text generation ---
  const componentsButtonText = useMemo(() => {
    if (components.length > 1) {
      return components
        .map((comp, index) => `组分${index + 1}: ${comp.ratio.toFixed(0)}%`)
        .join(' / ');
    }
    return '调节组分比例';
  }, [components]);

  const propertiesButtonText = useMemo(() => {
    const count = selectedProperties.size;
    if (count > 0) {
      return `已选 ${count} 项性质`;
    }
    return '选择预测性质 (待设置)';
  }, [selectedProperties]);
  // --- MODIFICATION END ---


  return (
    <div className="app-container">
        <header className="header">
            <h1>⚛️ 材料性质智能预测平台</h1>
            <p>Powered by Huawei Cloud EI & Watt Lab & AI4Sci Lab</p>
        </header>

        <div className="tabs">
            <button className={`tab-button ${activeTab === 'polymers' ? 'active' : ''}`} onClick={() => setActiveTab('polymers')}>🧪 聚合物性质预测</button>
            <button className={`tab-button ${activeTab === 'readme' ? 'active' : ''}`} onClick={() => setActiveTab('readme')}>📖 使用说明</button>
        </div>

        {activeTab === 'polymers' && (
            <div className="content">
                <div className="input-section">
                    <div className="input-mode-selector">
                        <label>高分子结构输入方式</label>
                        <div>
                            <button className={`mode-btn ${inputType === 'draw' ? 'active' : ''}`} onClick={() => setInputType('draw')}>图形化绘制</button>
                            <button className={`mode-btn ${inputType === 'smiles' ? 'active' : ''}`} onClick={() => setInputType('smiles')}>SMILES文本输入</button>
                        </div>
                    </div>

                    <div className="input-area-grid">
                        {inputType === 'draw' ? ( <div className="ketcher-wrapper"> <div className="ketcher-container"> <Editor staticResourcesUrl={'./'} structServiceProvider={structServiceProvider} onInit={(ketcher) => {  ketcherRef.current = ketcher;  if (smilesInput) { ketcher.setMolecule(smilesInput).catch(console.error); } }} /> </div> <button onClick={syncFromKetcher} className="sync-btn"> 分子结构确认 </button> </div> ) : ( <div className="smiles-input-wrapper"> <label>输入以"."分隔的SMILES字符串</label> <textarea className="smiles-textarea" placeholder="例如: *CC*.*CC(Cl)* 代表聚乙烯和PVC的混合物" value={smilesInput} onChange={(e) => setSmilesInput(e.target.value)}  /> </div> )}
                        <div className="viewer-wrapper"> <h3>三维分子视图</h3> <div className="viewer-container-3d"> <Molecule3DViewer smiles={smilesInput} /> </div> <p className="viewer-note">实时预览输入的分子结构</p> </div>
                    </div>
                </div>

                <div className="controls-section">
                    <div 
                        className="popover-container"
                        onMouseEnter={() => handlePopoverMouseEnter(componentsPopoverTimeoutRef, setComponentsPopoverVisible)}
                        onMouseLeave={() => handlePopoverMouseLeave(componentsPopoverTimeoutRef, setComponentsPopoverVisible)}
                    >
                        {/* --- MODIFICATION: Use dynamic text --- */}
                        <button 
                            className="control-btn"
                            disabled={components.length <= 1}
                        >
                            {componentsButtonText}
                        </button>
                        <div className={`popover-content ${isComponentsPopoverVisible ? 'visible' : ''}`}>
                            <div className="components-section">
                                <h2>组分比例调节 (总计: 100%)</h2>
                                <div className="components-list">
                                    {components.map((comp, index) => (
                                        <div key={comp.id} className="component-card">
                                            <div className="component-info"> <span className="component-index">组分 {index + 1}</span> <code className="component-smiles">{comp.smiles}</code> </div>
                                            <div className="component-slider"> <input type="range" min="0" max="100" step="0.1" value={comp.ratio} onChange={(e) => handleRatioChange(index, parseFloat(e.target.value))} /> <span className="component-ratio">{comp.ratio.toFixed(1)}%</span> </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </div>

                    <div 
                        className="popover-container"
                        onMouseEnter={() => handlePopoverMouseEnter(propertiesPopoverTimeoutRef, setPropertiesPopoverVisible)}
                        onMouseLeave={() => handlePopoverMouseLeave(propertiesPopoverTimeoutRef, setPropertiesPopoverVisible)}
                    >
                        {/* --- MODIFICATION: Use dynamic text --- */}
                        <button className="control-btn">
                           {propertiesButtonText}
                        </button>
                        <div className={`popover-content wide ${isPropertiesPopoverVisible ? 'visible' : ''}`}>
                            <div className="properties-section">
                                <h2>选择要预测的物化性质</h2>
                                <div className="properties-grid">
                                    {Object.entries(propertiesConfig).map(([category, props]) => (
                                        <div key={category} className="property-category">
                                            <h3>{category}</h3>
                                            {props.map(prop => (
                                                <label key={prop} className="checkbox-label"> <input type="checkbox" checked={selectedProperties.has(prop)} onChange={() => handlePropertyChange(prop)} /> {prop} </label>
                                            ))}
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <button className="calculate-btn" onClick={handleSubmit} disabled={isLoading || components.length === 0}>
                        {isLoading && <div className="spinner"></div>}
                        {isLoading ? '计算中...' : '开始计算'}
                    </button>
                </div>

                <div className="results-section">
                  {renderResults()}
                </div>
            </div>
        )}
        
        {activeTab === 'readme' && <ReadmeContent />}
    </div>
  );
}

export default App;